package org.ttitfly.zuoyue.service.room;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;
import org.ttitfly.workflow.Session;
import org.ttitfly.workflow.SessionEstablishment;
import org.ttitfly.workflow.engine.TaskRunUnit;
import org.ttitfly.workflow.engine.run.ProcessInstance;
import org.ttitfly.workflow.exception.NoSessionConnectedException;
import org.ttitfly.workflow.exception.ProcessRunException;
import org.ttitfly.zuoyue.entity.room.RoomProject;

@Component
@Transactional
public class RoomProjectFlowManager {
	
	private static final String ROOM_PROJECT = "室内分布建设";
	
	@Resource
	private SessionEstablishment sessionEstablishment;
	
	@Resource
	private RoomProjectManager roomProjectManager;

	public void startRommProject(RoomProject roomProject) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("roomProject", roomProject);
		data.put("name", roomProject.getName());
		Session session = sessionEstablishment.connect(SpringSecurityUtils.getCurrentUserName(), data);
		ProcessInstance pi = null;
		try {
			pi = session.start(ROOM_PROJECT);
		} catch (ProcessRunException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				session.close();
			} catch (NoSessionConnectedException e) {
			}
		}
		roomProject.setProcessInstanceId(pi.getId());
		roomProjectManager.update(roomProject);
	}
	
	public void process(int taskId, RoomProject roomProject, String actionName, String remark) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("roomProject", roomProject);
		data.put(TaskRunUnit.TASK_REMARK_KEY, remark);
		Session session = sessionEstablishment.connect(SpringSecurityUtils.getCurrentUserName(), data);
		try {
			if (StringUtils.isBlank(actionName)) {
				session.execute(taskId);
			} else {
				session.execute(taskId, actionName);
			}
		} catch (ProcessRunException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				session.close();
			} catch (NoSessionConnectedException e) {
			}
		}
	}
}
